<template>
  <div class="responsive-layout">
    <div class="kp">
      <div class="responsive-layout">
        <el-card class="box-card">
          <div class="item">
            <el-form
              :inline="true"
              :model="formInline"
              class="demo-form-inline"
            >
            </el-form>

            <!-- 操作按钮 -->
            <el-row>
              <div class="grid-content bg-purple">
                <div style="margin-bottom: 10px">
                  <el-button type="success" @click="XinZen()">新增</el-button>
                </div>
              </div>
            </el-row>

            <div>
              <!-- 表单数据-->

              <el-table :data="rolesData" border style="width: 100%">
                <el-table-column prop="rolesID" label="编号"></el-table-column>
                <el-table-column
                  prop="rolesName"
                  label="角色名称"
                ></el-table-column>
                <el-table-column
                  prop="rolesInstruction"
                  label="概要"
                ></el-table-column>
                <el-table-column fixed="right" label="操作">
                  <template slot-scope="scope">
                    <el-button
                      @click="handleClick(scope.row)"
                      type="primary"
                      size="small"
                      >编辑</el-button
                    >
                    <el-button
                      type="danger"
                      size="small"
                      @click="Delete(scope.row)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
              <div class="block">
                <el-pagination
                  class="pagination"
                  @size-change="change"
                  @current-change="Ymchange"
                  :current-page="currentPage"
                  :page-sizes="[10, 15, 20, 50]"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="rows"
                >
                </el-pagination>
              </div>
              <el-drawer title="新增" :visible.sync="drawer1" size="35%">
                <!-- 卡片 -->
                <el-card class="box-card" style="width: 95%; margin: 0 auto">
                  <div>
                    <el-form label-width="80px" :model="rbac_Roles">
                      <el-form-item label="角色名称">
                        <el-input v-model="rbac_Roles.rolesName"></el-input>
                      </el-form-item>
                      <el-form-item label="简介">
                        <el-input
                          v-model="rbac_Roles.rolesInstruction"
                        ></el-input>
                      </el-form-item>
                    </el-form>
                    <el-tree
                      :data="treeData"
                      show-checkbox
                      node-key="id"
                      ref="treeRef2"
                      :default-expanded-keys="defaultExpandedKeys"
                      :default-checked-keys="defaultCheckedKeys"
                      :props="defaultProps"
                      @check-change="handleCheckChange2"
                    ></el-tree>
                  </div>
                </el-card>

                <div style="float: right; margin-right: 40px; margin-top: 40px">
                  <el-button @click="drawer = false">取消</el-button>
                  <el-button type="success" @click="successadd">保存</el-button>
                </div>
              </el-drawer>

              <el-drawer title="编辑权限" :visible.sync="drawer2" size="35%">
                <!-- 卡片 -->
                <el-card class="box-card" style="width: 95%; margin: 0 auto">
                  <div>
                    <el-link type="success">编辑角色权限</el-link>
                    <el-tree
                      :data="treeData"
                      show-checkbox
                      node-key="id"
                      ref="treeRef"
                      :default-expanded-keys="defaultExpandedKeys"
                      :default-checked-keys="defaultCheckedKeys1"
                      :props="defaultProps"
                      @check-change="handleCheckChange"
                    ></el-tree>
                  </div>
                </el-card>

                <div style="float: right; margin-right: 40px; margin-top: 40px">
                  <el-button @click="quxiao">取消</el-button>
                  <el-button type="success" @click="confirmChanges"
                    >保存</el-button
                  >
                </div>
              </el-drawer>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import $http from "@/routers/base";
export default {
  data() {
    return {
      treeData: [], // 用于存储从API获取到的树形结构数据  （新增）
      defaultExpandedKeys: [], // 初始展开的节点ID列表
      defaultCheckedKeys: [], // 初始选中的节点ID列表
      defaultCheckedKeys1: [],
      defaultProps: {
        // 设置el-tree如何解释数据
        children: "children",
        label: "authName",
      },
      pid: 0,
      rbac_Roles: {
        rolesID: 0,
        rolesName: "",
        rolesInstruction: "",
      },
      drawer1: false,
      drawer2: false,
      Adate: [],
      formInline: {
        rolesID: 0,
        rolesName: "",
      },
      //时间控件转换格式
      value1: [],
      qsj: "",
      hsj: "",
      mys: 4,
      dqy: 1,
      zts: 0,
      GYSdate: [],
      Idbh: [], //存储批量编号
      Ztzd: [], //储存批量状态
      kuang: false, //默认关闭弹框
      ShenHezt: "",
      ShenHeyj: "",
      ShenHeman: "",
      ShenHesj: "",
      loading: true, //刷新加载
      rolesData: [],
      kong: [],
      kp: [],
      kp3: [],
      updTree: [], // 修改时选中的所有权限
      pdd: 0,
      currentPage: 1, //当前页
      pageSize: 10, //每页显示数
      rows: 0, //总行数
    };
  },
  methods: {
    //删除角色和对应权限
    Delete(row) {
      $http
        .delete("QuanXian/deleterblo?roid=" + row.rolesID)
        .then((res) => {
          alert("删除成功!");
          this.FenYecha();
        })
        .catch((err) => {
          alert("删除失败"), console.log(err);
        });
    },
    //分页查询
    FenYecha() {
      this.where = "1=1";
      $http
        .get("QuanXian/getFenYe", {
          params: {
            currentPage: this.currentPage,
            pageSize: this.pageSize,
            where: this.where,
          },
        })
        .then((res) => {
          this.rolesData = res.rolesData;
          this.rows = res.rows;
        })
        .catch((error) => {
          console.error("Error fetching client data: ", error);
        });
    },
    change: function (size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.FenYecha();
    },
    Ymchange: function (page) {
      this.currentPage = page;
      this.FenYecha();
    },
    successadd() {
      $http
        .post("QuanXian/addrole", this.rbac_Roles, {
          headers: {
            "Content-Type": "application/json",
          },
        })
        .then((res) => {
          alert("添加成功!!");
          this.FenYecha();
          this.queryroid();
          this.drawer1 = false;
        });
    },
    queryroid() {
      $http
        .get("QuanXian/Rolesselectc")
        .then((response) => {
          this.pdd = response.rolesID;
          $http
            .post("QuanXian/addquan?pid=" + this.pdd, this.kp3, {
              headers: {
                "Content-Type": "application/json",
              },
            })
            .then((res) => {});
          console.log("sb" + this.pdd);
        })
        .catch((error) => {
          alert("查询失败");
          console.error(error);
        });
    },

    /**
     * 选项改变事件
     */
    handleCheckChange() {
      this.kp = this.$refs.treeRef.getCheckedKeys();

      console.log("选中的值", this.kp);
    },
    handleCheckChange2() {
      this.kp3 = this.$refs.treeRef2.getCheckedKeys();
      console.log("选中的值", this.kp3);
    },
    confirmChanges() {
      $http
        .post("QuanXian/addquan?pid=" + this.pid, this.kp, {
          headers: {
            "Content-Type": "application/json",
          },
        })
        .then((res) => {
          alert("修改成功!");
          this.FenYecha();
        });
    },
    // 向后端发送更新的权限
    updateRolePermissions(keys) {},

    quxiao() {
      this.drawer2 = false;

      this.defaultCheckedKeys1 = this.kong;
    },
    handleClick(row) {
      this.pid = row.rolesID;
      console.log("sb" + this.idd);
      $http
        .get("QuanXian/QianBian?pid=" + row.rolesID) // 调用API获取树形数据
        .then((response) => {
          // 确保响应数据是正确的，并且提取出需要的数据
          this.defaultCheckedKeys1 = response;
          this.drawer2 = true;
        })
        .catch((error) => {
          alert("查询失败"); // 显示失败警告
          console.error(error); // 在控制台打印错误信息
        });
    },
    XinZen() {
      this.drawer1 = true;
    },
    //树状结构
    quanxian() {
      // 假设$http是一个可用的HTTP请求工具
      $http
        .get("QuanXian/TressSelect") // 调用API获取树形数据
        .then((response) => {
          // 确保响应数据是正确的，并且提取出需要的数据
          this.treeData = response;
        })
        .catch((error) => {
          alert("查询失败"); // 显示失败警告
          console.error(error); // 在控制台打印错误信息
        });
    },
    submitForm() {
      $http
        .get("QuanXian/UserSelects")
        .then((res) => {
          this.rolesData = res;
          console.log(res);
        })
        .catch((err) => {
          alert("查询失败"), console.log(err);
        });
    },

    //刷新
    ShuaXin() {
      this.loading = true;
      this.QingKong();

      setTimeout(() => {
        this.loading = false;
      }, 2000);
    },
    //清空
    QingKong() {
      (this.formInline.region = "\0"),
        (this.formInline.GYS = ""),
        (this.formInline.user = ""),
        (this.qsj = ""),
        (this.hsj = "");
    },
    querymohu() {
      this.FenYecha();
    },
    //获取多选中的编号,状态
    Huoqvxinxi() {
      this.Idbh = []; //存储序号(id)
      this.Ztzd = []; //存储状态
      const selectedRows = this.$refs.AdateMZ.selection; // 获取选中的行数据
      const data = selectedRows.map((row) => {
        return { 序号: row.id };
      }); //获取序号
      const data2 = selectedRows.map((row) => {
        return { 状态: row.sure_state };
      }); //获取状态

      for (let i = 0; i < data.length; i++) {
        this.Idbh.push(data[i]["序号"]);
      }
      for (let i = 0; i < data2.length; i++) {
        this.Ztzd.push(data2[i]["状态"]);
      }
      console.log("序号：" + this.Idbh);
      console.log("状态：" + this.Ztzd);
    },
    //条数改变
    handleSizeChange(val) {
      this.mys = val;
      this.cha();
    },
    //页数改变
    handleCurrentChange(val) {
      this.dqy = val;
      this.FenYecha();
    },
    //字段处理
    formatItemNames(itemNames) {
      if (itemNames && itemNames.length > 5) {
        return itemNames.slice(0, 5) + "...";
      } else if (itemNames) {
        return itemNames;
      } else {
        return "";
      }
    },
    //当前时间获取 年月日
    dangqianTime() {
      const date = new Date();
      const year = date.getFullYear();
      const month = ("0" + (date.getMonth() + 1)).slice(-2);
      const day = ("0" + date.getDate()).slice(-2);

      this.currenTime = `${year}-${month}-${day}`;
      this.ShenHesj = this.currenTime;
    },
  },
  created() {
    // 在组件创建时调用quanxian方法获取数据
    this.quanxian();
  },
  mounted() {
    this.FenYecha();
    this.formatItemNames();
    this.ShuaXin();
  },
};
</script>

<style scoped></style>
